<template>
  <div class="edit-department">
    <a-modal
      width="800px"
      :title="updateTitles"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="spinning" tip="正在加载数据中...">
        <a-form :form="form">
          <a-row :gutter="10">
            <!-- fix: 修改时服务名称不能修改 -->
            <a-col :span="24">
              <a-form-item label="名称" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
                <a-input
                  v-decorator="[
                    'NAME',
                    {
                      rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入服务名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="介绍" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
                <a-input
                  v-decorator="[
                    'MS',
                    {
                      rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入服务名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="封面图片上传" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-upload
                  :action="action"
                  :headers="headers"
                  list-type="picture-card"
                  :file-list="fileList"
                  @preview="handlePreview"
                  @change="handleUploadChange1($event, index)"
                >
                  <div v-if="fileList.length < 1">
                    <a-icon type="plus" />
                    <div class="ant-upload-text">点击上传</div>
                  </div>
                </a-upload>
                <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                  <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
              </a-form-item>
            </a-col>
            <!-- <a-col :span="24">
              <a-form-item
                v-for="(k, index) in form.getFieldValue('uflist')"
                :key="index"
                v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
                :label="index === 0 ? '案例详情' : ''"
                :required="false"
              >
                <a-col :span="10">
                  <a-form-item label="案例细分" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                    <a-input
                      v-model="dynamicForm[index].CS_WJMC"
                      placeholder=""
                      style="width: 60%; margin-right: 8px"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="10">
                  <a-form-item label="图片" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                    <a-upload
                      :multiple="false"
                      :action="action"
                      :default-file-list="defaultFileList[index]"
                      :headers="headers"
                      :remove="handleUploadRemove1"
                      @change="handleUploadChange($event, index)"
                    >
                      <a-button type="primary"> <a-icon type="upload" /> 点击上传</a-button>
                    </a-upload>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-icon
                    v-if="form.getFieldValue('uflist').length > 1"
                    class="dynamic-delete-button"
                    type="minus-circle-o"
                    :disabled="form.getFieldValue('uflist').length === 1"
                    @click="() => remove(k)"
                  />
                </a-col>
              </a-form-item>
              <a-form-item v-bind="formItemLayoutWithOutLabel" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-button type="dashed" style="width: 60%" @click="addformItem">
                  <a-icon type="plus" /> 添加案例详情
                </a-button>
              </a-form-item>
            </a-col> -->
            <a-col :span="24">
              <div class="a-df">
                <div class="transbtn transbtn-left" @click="itemtransleft()">
                  <a-icon type="left" />
                </div>
                <div class="upload-items">
                  <div
                    class="upload-item"
                    :class="{ 'upload-item-show': item.isshow }"
                    @click="uploadItemShow(item)"
                    :style="columnItem"
                    v-for="item in FWLBTBparameter"
                    :key="item.ID"
                  >
                    {{ item.CSMC }}
                  </div>
                </div>
                <div class="transbtn transbtn-right" @click="itemtransright()">
                  <a-icon type="right" />
                </div>
              </div>
              <div
                class="upload-main"
                v-for="(item, index) in FWLBTBparameter"
                :key="item.ID"
                :style="{ display: item.isshow ? 'block' : 'none' }"
              >
                <a-upload
                  name="avatar"
                  class="avatar-uploader"
                  :default-file-list="item.fileList"
                  :multiple="false"
                  list-type="picture-card"
                  :headers="headers"
                  :show-upload-list="false"
                  :action="action"
                  @change="handleUploadChange($event, index)"
                >
                  <div v-if="item.fileList.length < 1 ">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">点击上传</div>
                  </div>
                  <img v-else :src="item.fileList[0].url" alt="avatar" />
                </a-upload>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import { setDepartments, getDepartmentSelect } from '@/api/system'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { postAddXMALApi, getCsglListApi, postupdateXMALApi, getFWLBDrptApi, getXMALListApi } from '@/api/service'
import { validFixedTelphone, validTelphone } from '@/utils/validate'

let id = 0

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      confirmLoading: false,
      treeName: '',
      defaultFileList: [],
      previewVisible: false,
      previewImage: '',
      fileListt: [],
      dynamicForm: [],
      columnItem: { transform: `translateX(columntransform)` },
      headers: {
        Authorization: storage.get(ACCESS_TOKEN),
        GF: this.$store.getters.userid,
      },
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      action: process.env.VUE_APP_API_BASE_URL + '/api/uploadFile/UploadPictures',
      Imgs: '',
      fileList: [],
      parentTreeList: [
        {
          NAME: '无',
          ID: 0,
          children: [],
        },
      ],
      levelList: [],
      casesList: [],
      iconurl: '',
      FWLBTBparameter: [],
      columntransform: 0,
      // form: this.$form.createForm(this, { name: 'department' }),
      formItemLayout: {
        labelCol: {
          xs: { span: 4 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 20 },
          sm: { span: 20 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 20, offset: 0 },
          sm: { span: 20, offset: 4 },
        },
      },
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'dynamic_form_item' })
    this.form.getFieldDecorator('uflist', { initialValue: [], preserve: true })
  },
  watch: {
    propsData: function () {
      this.fetchDepartment()
    },
  },
  computed: {
    // levelList:treeNameLookup(),
    updateTitles: function () {
      const {
        propsData: { type },
      } = this
      if (type === 'add') {
        return '新增案例'
      } else {
        return '修改案例'
      }
    },
  },
  methods: {
    remove(k) {
      const { form } = this
      // can use data-binding to get
      const uflist = form.getFieldValue('uflist')
      // We need at least one passenger
      if (uflist.length === 1) {
        return
      }
      // can use data-binding to set
      form.setFieldsValue({
        uflist: uflist.filter((key) => key !== k),
      })
      this.dynamicForm.splice(-1, 1)
      console.log('this.dynamicForm', this.dynamicForm)
    },
    uploadItemShow(item) {
      for (const ite of this.FWLBTBparameter) {
        ite.isshow = false
      }
      item.isshow = true
    },
    itemtransleft() {
      if (this.columntransform >= 0) {
        return false
      }
      this.columntransform += 120
      this.columnItem.transform = 'translateX(' + this.columntransform + 'px)'
    },
    itemtransright() {
      if (this.columntransform <= -120) {
        return false
      }
      this.columntransform -= 120
      this.columnItem.transform = 'translateX(' + this.columntransform + 'px)'
    },
    addformItem() {
      const { form } = this
      const {
        propsData: { type, record },
      } = this
      this.dynamicForm.push({
        CS_WJMC: '',
        WJLJ: '',
        SCYH: this.$store.getters.loginName,
        CS_WJLX: this.FWLBTBparameter[0].ID,
        TNAME: 'XMAL',
      })
      const uflist = form.getFieldValue('uflist')
      if (type != 'update') {
        const nextKeys = uflist.concat(id++)
        form.setFieldsValue({
          uflist: nextKeys,
        })
      }
    },
    fetchDepartment() {
      // this.spinning = true
      const {
        propsData: { type, record },
        form: { setFieldsValue },
      } = this
      if (type === 'update') {
        // this.dynamicForm = record.uflist
        this.fileList = [
          {
            uid: '-1',
            name: record.Imgs,
            url: process.env.VUE_APP_API_BASE_URL + record.Imgs,
            status: 'done',
            response: {
              data: [record.Imgs],
            },
          },
        ]
        this.Imgs = record.Imgs
        this.defaultFileList = record.uflist.map((item) => [
          { uid: '-1', name: item.CS_WJMC, url: process.env.VUE_APP_API_BASE_URL + item.WJLJ, status: 'done' },
        ])
      }
      getCsglListApi({
        ClassKey: 'XMAL',
      })
        .then((res) => {
          this.FWLBTBparameter = res.data
          if (type === 'update') {
            for (const item of record.uflist) {
              for (const ite of this.FWLBTBparameter) {
                if (ite.fileList && ite.fileList.length > 0){
                  
                }else if (item.CS_WJMC == ite.CSMC &&  item.WJLJ != '') {
                console.log('item.CS_WJMC',item.CS_WJMC,ite.CSMC,item.WJLJ);
                  this.$set(ite, 'fileList', [
                    {
                      uid: '-1',
                      name: item.CS_WJMC,
                      url: process.env.VUE_APP_API_BASE_URL + item.WJLJ,
                      status: 'done',
                      response: {
                        data: [item.WJLJ],
                      },
                    },
                  ])
                } else {
                  this.$set(ite, 'fileList', [])
                }
              }
            }
            console.log('this.FWLBTBparameter',this.FWLBTBparameter);
          } else {
            for (const ite of this.FWLBTBparameter) {
              this.$set(ite, 'fileList', [])
            }
          }
          for (const item of this.FWLBTBparameter) {
            this.$set(item, 'isshow', false)
          }
          this.FWLBTBparameter[0].isshow = true
          this.$nextTick(() => {
            setFieldsValue(pick(record, ['NAME', 'uflist', 'MS']))
          })
        })
        .catch(() => {
          this.$message.error('网络请求失败, 请稍后重试')
        })
        .finally(() => {
          this.spinning = false
        })
    },
    //上传
    handleUploadRemove() {
      this.form.setFieldsValue({
        WJLJ: this.fileListt.url,
      })
      return true
    },
    //上传
    handleUploadRemove1() {
      return true
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleUploadChange(info, index) {
      let fileListt = [...info.fileList]
      fileListt = fileListt.slice(-1)
      fileListt = fileListt.map((file) => {
        if (file.response) {
          const url = process.env.VUE_APP_API_BASE_URL + file.response.data[0]
          // this.dynamicForm[index].WJLJ = file.response.data[0]
          file.url = url
        }
        return file
      })
      this.FWLBTBparameter[index].fileList = fileListt
    },
    handleUploadChange1(info, index) {
      let fileListt = [...info.fileList]
      fileListt = fileListt.slice(-1)
      fileListt = fileListt.map((file) => {
        if (file.response) {
          console.log('file.response', file.response)
          const url = process.env.VUE_APP_API_BASE_URL + file.response.data[0]
          this.Imgs = file.response.data[0]
          file.url = url
        }
        return file
      })
      this.fileList = fileListt
    },
    handleSubmit() {
      const {
        form: { validateFields },
        propsData: { type, record },
        $message,
      } = this
      validateFields((err, values) => {
        console.log('values', values)
        if (!err) {
          this.confirmLoading = true
          const submitData = Object.assign({}, values, {
            Contype: this.$store.getters.loginName,
            Type: '0',
          })
          for (const item of this.FWLBTBparameter) {
            this.dynamicForm.push({
              CS_WJMC: item.CSMC,
              WJLJ: item.fileList.length > 0 ? item.fileList[0].response.data[0] : '',
              SCYH: this.$store.getters.loginName,
              CS_WJLX: this.FWLBTBparameter[0].ID,
              TNAME: 'XMAL',
            })
          }
          if (type === 'update') {
            console.log('22222222222222222222222222')
            ;(submitData.ID = record.ID), console.log('this.dynamicForm', this.dynamicForm)
            postupdateXMALApi(
              Object.assign({}, values, {
                ID: record.ID,
                Imgs: this.Imgs,
                uflist: this.dynamicForm,
              })
            )
              .then((res) => {
                if (res.code === 200) {
                  $message.success(res.message || '提交成功', 3)
                  this.handleCancel()
                  this.$parent.$parent.$refs.table.refresh(true)
                } else {
                  $message.error(res.message || '提交失败', 3)
                }
              })
              .catch((err) => {
                $message.error(err, 3)
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            console.log('this.dynamicForm', this.dynamicForm)
            postAddXMALApi(
              Object.assign({}, values, {
                Imgs: this.Imgs,
                uflist: this.dynamicForm,
              })
            )
              .then((res) => {
                if (res.code === 200) {
                  $message.success(res.message || '提交成功', 3)
                  this.handleCancel()
                  this.$parent.$parent.$refs.table.refresh(true)
                } else {
                  $message.error(res.message || '提交失败', 3)
                }
              })
              .catch((err) => {
                $message.error(err, 3)
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style lang="less" scoped>
.upload-items::-webkit-scrollbar {
  display: none; /* 对于WebKit浏览器 */
}

.upload-items {
  scrollbar-width: none; /* 对于IE和Edge */
}
/* 兼容Firefox */
.upload-items {
  overflow: auto;
}
.upload-items {
  display: flex;
  background: #f6f7fb;
  // height: 50px;
  line-height: 40px;
  overflow-x: auto;
  position: relative;
  // width: 300px;
  .upload-item-show {
    background: #fff;
    border: solid 1px #dde0e1;
    border-bottom: none !important;
  }

  .upload-item {
    padding: 0 20px;
    flex-wrap: nowrap;
    height: 40px;
    white-space: nowrap;
    border-bottom: solid 1px #dde0e1;
    cursor: pointer;
  }
}
.transbtn {
  padding: 0 10px !important;
  flex-wrap: nowrap;
  height: 40px;
  line-height: 40px;
  white-space: nowrap;
  border-bottom: solid 1px #dde0e1;
  background: #f6f7fb;
  cursor: pointer;
}
.upload-main {
  margin: 20px;
  width: 500px;
  max-height: 200px;
  img {
    max-width: 100%;
    max-height: 200px;
  }
}
.avatar-uploader > .ant-upload {
  width: 1208px;
  height: 1208px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
<style lang="less">
.upload-main {
  .ant-upload.ant-upload-select-picture-card {
    width: 500px !important;
    height: 200px !important;
  }
}
</style>
